package com.huiyeji.xlsx;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class XLSXWorkSpace {

    private final Workbook wk;

    private final Sheet st;

    private Row pdr;

    private Row pnr;

    private final List<String> pdl = new ArrayList<String>();

    private final List<String> pnl = new ArrayList<String>();
    /**
     * 总行数
     */
    private final int rC;

    /**
     * 总列数
     */
    private final int cC;

    protected XLSXWorkSpace(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            this.wk = new XSSFWorkbook(inputStream);
            if (wk.getNumberOfSheets() == 0){
                throw new XLSXParseException("未找到sheet");
            }
            this.st = wk.getSheetAt(0);
            this.rC = st.getLastRowNum() + 1;
            if (this.rC <= 2){
                throw new XLSXParseException("无有效数据行");
            }
            this.pdr = st.getRow(0);
            this.pnr = st.getRow(1);
            this.cC = this.pnr.getLastCellNum();

            for (int i = 0; i < cC; i++){
                pnl.add(pnr.getCell(i).getStringCellValue());
                pdl.add(pdr.getCell(i).getStringCellValue());
            }
        } catch (Exception e) {
            throw new XLSXParseException("文件操作空间创建失败");
        }
    }

    public a gSci(int columnNumber){
        return new a(pdl.get(columnNumber),pnl.get(columnNumber),null,columnNumber);
    }

    public boolean containsColumn(String columnName){
        return this.pnl.contains(columnName);
    }

    public boolean containsEveryColumns(String...columnNames){
        for (String columnName : columnNames) {
            if (!this.pnl.contains(columnName)){
                return false;
            }
        }
        return true;
    }

    public boolean containsAnyColumns(String...columnNames){
        for (String columnName : columnNames) {
            if (this.pnl.contains(columnName)){
                return true;
            }
        }
        return false;
    }

    public Workbook getWorkbook() {
        return wk;
    }

    public Sheet getSheet() {
        return st;
    }

    public int getRowCount() {
        return rC;
    }

    public int getColumnCount() {
        return cC;
    }

    public List<String> getPropertyNameList() {
        return pnl;
    }
}
